<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/6/26
 * Time: 13:25
 */

namespace App\Http\Controllers\Api\v1\Pay;

use App\Tools\Orders as OrdersLib;
use App\Models\Api\Active;
use App\Models\Api\Orders as OrdersModel;
use App\Models\TOrders;
use App\Models\Api\Recode;
use App\Models\Api\LanmeiCounselorProblem;
use Cache;
use DB;
use App\Models\Api\Rectification as RectificationModel;
use App\Models\Api\LanmeiUserAccountRecord;
use App\Tools\PayCheckSign;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
/**
 * 支付回调相关接口
 * Class Notify
 * @package app\pay\controller
 */
class NotifyController extends Controller
{
    protected $config = [
        'APP' => 'wxpay',
        'JSAPI' => 'wxwebpay',
        'MWEB' => 'wxwebpay'
    ];

    /**
     * 微信支付成功以后的回调
     *  <xml>
     *      <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
     *      <attach><![CDATA[支付测试]]></attach>
     *      <bank_type><![CDATA[CFT]]></bank_type>
     *      <fee_type><![CDATA[CNY]]></fee_type>
     *      <is_subscribe><![CDATA[Y]]></is_subscribe>
     *      <mch_id><![CDATA[10000100]]></mch_id>
     *      <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
     *      <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
     *      <out_trade_no><![CDATA[1409811653]]></out_trade_no>
     *      <result_code><![CDATA[SUCCESS]]></result_code>
     *      <return_code><![CDATA[SUCCESS]]></return_code>
     *      <sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
     *      <sub_mch_id><![CDATA[10000100]]></sub_mch_id>
     *      <time_end><![CDATA[20140903131540]]></time_end>
     *      <total_fee>1</total_fee><coupon_fee><![CDATA[10]]></coupon_fee>
     *      <coupon_count><![CDATA[1]]></coupon_count>
     *      <coupon_type><![CDATA[CASH]]></coupon_type>
     *      <coupon_id><![CDATA[10000]]></coupon_id>
     *      <coupon_fee><![CDATA[100]]></coupon_fee>
     *      <trade_type><![CDATA[JSAPI]]></trade_type>
     *      <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
     *  </xml>
     * @return string xml
     */
    public function wechat()
    {
        $returnStatus = ['return_code' => 'FAIL', 'return_msg' => '签名失败'];

        $xml = file_get_contents('php://input');
        \Log::info('weixin_Notify:' . var_export($xml, true));
       // \Log::info(var_export($wxConfig, true));

        //检验xml格式
        $xml_parser = xml_parser_create();
        if (!xml_parse($xml_parser, $xml, true))
        {
            $data = [];
        } else
        {
            $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        }
        //验签名。默认支持MD5
        $wxpayConfig = OrdersLib::getPayConfig('wx');

        $wxConfig = $wxpayConfig[$this->config[$data['trade_type']]];

        if (!empty($data) && (new PayCheckSign)->weixin($data, $wxConfig['api_key']))
        {
            if ($data['return_code'] == 'SUCCESS'
                && $data['result_code'] == 'SUCCESS'
                && $data['appid'] == $wxConfig['appid']
                && $data['mch_id'] == $wxConfig['mchid'])
            {
                $out_trade_no = $data['out_trade_no'];// 订单号
                $pay_time = strtotime($data['time_end']);// 支付完成时间 转换为时间戳
                $total_fee = $data['total_fee'] / 100;// 订单总金额 单位为分

               try {
                // 查询是否存在这个充值订单
                $rechargeOrder = (new TOrders())->where(['order_id' => $out_trade_no, 'total_amount' => $total_fee])->first()->toArray();

                if ($rechargeOrder) {
                    // 如果充值并且已经支付写入叠加余额
                    (new LanmeiUserAccount())->where(['uid' => $rechargeOrder['uid']])->increment('balance', $total_fee)->increment('total_amount', $total_fee);
                     // 获取用户账户最新的信息
                    $accountInfos =   (new LanmeiUserAccount())->where('uid', $rechargeOrder['uid'])->get(['id','uid','total_amount','balance'])->toArray();
                        // 账户流水
                        $recordData = [
                            'create_time' => time(),
                            'record_type' => 10,
                            'gid' => $rechargeOrder['gid'],
                            'price' => $total_fee,
                            'balance' => $accountInfos['balance'],
                            'account_id' => $accountInfos['id'],
                            'extend' => '用户充值记录'
                        ];
                     // 并且写入流水清单
                    (new LanmeiUserAccountRecord())->create($recordData);
                    $returnStatus = 'success';
                    echo $returnStatus;
                    exit;
                } else {
                    // 如果不是充值订单检查服务订单
                    $order = (new OrdersModel())->where(['order_id' => $out_trade_no, 'total_amount' => $total_fee])->first();
                }
                  } catch (\Exception $e) {
                      $order = [];
                     \Log::info('ali支付回调，获取订单信息失败：' . $e->getMessage());
              }

                //检查订单类型
                $num = $this->check_type($out_trade_no);

                if ($order && $order['status'] === 0)
                {
                    // 回调逻辑处理
                    $dbStatus = $this->notify_handle([
                        'oid' => $order['id'],
                        'uid' => $order['uid'],
                        'reid' => $order['reid'],
                        'fid' => $order['fid'],
                        'num' => $num,
                        'order_id' => $out_trade_no,
                        'pay_time' => $pay_time,
                        'orderInfo' => $order
                    ]);
                    if ($dbStatus)
                    {
                        $returnStatus = [
                            'return_code' => 'SUCCESS',
                            'return_msg' => 'OK'
                        ];
                    }
                }
            }
        } else
        {
            \Log::info(var_export($xml, true));
            \Log::info(var_export($wxConfig, true));
            return false;
        }
        return $this->arrayToXml($returnStatus);
    }

    /**
     * 支付宝支付回调修改订单状态
     * notify_time 通知时间 Date 是 通知的发送时间。格式为yyyy-MM-dd HH:mm:ss 2015-14-27 15:45:58
     * notify_type 通知类型 String(64) 是 通知的类型 trade_status_sync
     * notify_id 通知校验ID String(128) 是 通知校验ID ac05099524730693a8b330c5ecf72da9786
     * app_id 支付宝分配给开发者的应用Id String(32) 是 支付宝分配给开发者的应用Id 2014072300007148
     * charset 编码格式 String(10) 是 编码格式，如utf-8、gbk、gb2312等 utf-8
     * version 接口版本 String(3) 是 调用的接口版本，固定为：1.0 1.0
     * sign_type 签名类型 String(10) 是 商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2 RSA2
     * sign 签名 String(256) 是 请参考异步返回结果的验签 601510b7970e52cc63db0f44997cf70e
     * trade_no 支付宝交易号 String(64) 是 支付宝交易凭证号 2013112011001004330000121536
     * out_trade_no 商户订单号 String(64) 是 原支付请求的商户订单号 6823789339978248
     * trade_status 交易状态 String(32) 否 交易目前所处的状态，见交易状态说明 TRADE_CLOSED
     *      WAIT_BUYER_PAY 交易创建，等待买家付款 || TRADE_CLOSED  未付款交易超时关闭，或支付完成后全额退款 || TRADE_SUCCESS   交易支付成功 || TRADE_FINISHED     交易结束，不可退款
     */
   public function ali(Request $request)
    {
        $param = $request->all();

        $returnStatus = 'fail';
        // 签名成功
        if ((new PayCheckSign)->ali($param))
        {
        \Log::info('weixin_Notify:' . var_export($param, true));
        \Log::info(var_export($param, true));
            $aliConfig = OrdersLib::getPayConfig('ali');
            $trade_status = $param['trade_status'] ?? '';
            if ($trade_status == 'TRADE_SUCCESS')
            {
                //===============如果支付成功，修改订单状态===========================//
                $out_trade_no = $param['out_trade_no'] ?? '';//获取订单号
                $app_id = $param['app_id'] ?? '';
                $seller_email = $param['seller_email'] ?? '';
                $seller_id = $param['seller_id'] ?? '';
                $total_amount = $param['total_amount'] ?? '';
                $pay_time = strtotime($param['gmt_payment']);

               try {
                // 查询是否存在这个充值订单
                $rechargeOrder = (new TOrders())->where(['order_id' => $out_trade_no, 'total_amount' => $total_amount])->first();

                if ($rechargeOrder) {
                    // 如果充值并且已经支付写入叠加余额
                    (new LanmeiUserAccount())->where(['uid' => $rechargeOrder['uid']])->increment('balance', $total_amount)->increment('total_amount', $total_amount);
                     // 获取用户账户最新的信息
                    $accountInfos =   (new LanmeiUserAccount())->where('uid', $rechargeOrder['uid'])->get(['id','uid','total_amount','balance'])->toArray();
                        // 账户流水
                        $recordData = [
                            'create_time' => time(),
                            'record_type' => 10,
                            'gid' => $rechargeOrder['gid'],
                            'price' => $total_amount,
                            'balance' => $accountInfos['balance'],
                            'account_id' => $accountInfos['id'],
                            'extend' => '用户充值记录'
                        ];
                     // 并且写入流水清单
                    (new LanmeiUserAccountRecord())->create($recordData);
                    $returnStatus = 'success';
                    echo $returnStatus;
                    exit;
                } else {
                    // 如果不是充值订单检查服务订单
                    $order = (new OrdersModel())->where(['order_id' => $out_trade_no, 'total_amount' => $total_amount])->first();
                }
                  } catch (\Exception $e) {
                      $order = [];
                     \Log::info('ali支付回调，获取订单信息失败：' . $e->getMessage());
              }
                if (
                    $order
                    && $order['total_amount'] == $total_amount
                    && $app_id == $aliConfig['app_id']
                    && $seller_email == $aliConfig['seller_email']
                    && $seller_id == $aliConfig['seller_id']
                )
                {
                    //检查订单类型
                    $num = $this->check_type($out_trade_no);

                    // 回调逻辑处理
                    if ($order && $order['status'] === 0)
                    {
                        $dbStatus = $this->notify_handle([
                            'oid' => $order['id'],
                            'uid' => $order['uid'],
                            'reid' => $order['reid'],
                            'fid' => $order['fid'],
                            'num' => $num,
                            'order_id' => $out_trade_no,
                            'pay_time' => $pay_time,
                            'orderInfo' => $order
                        ]);
                    }

                    if ($dbStatus)
                    {
                        $returnStatus = 'success';
                    }
                }
            }
        }
        echo $returnStatus;
        exit;
    }

    /**
     * 京东支付回调
     * demo xml
     * <?xml version="1.0" encoding="UTF-8" ?><jdpay>  <version>V2.0</version>  <merchant>110148035005</merchant>  <result>    <code>000000</code>    <desc>success</desc>  </result>  <encrypt>M2JlZTE1NTZkMTdmOGYzN2ZkN2YyY2IwNTFkMTI0MzgwYTA5ZjAxM2ZhNWI5NmUyNjVmNzg5ZmIyY2E4OWJkMmM5N2VmYWVlMDViMzJhNWQwYWVhZDI4YTE5MjRhY2QzZjAyZmMxMjcyODVhNjM4ZWE3ZDkxNjk1N2VlYTVlMTQ0MzMzNWFlODg2MzAzOTE1ZDQyNDM3NzlmZmM2NzA1NjNmNTA2MGVjZjRmOWFlZjVkZDNkZjM2NjZlYTU4Mjk1NDZjOTUxMmJkOTI4NzM0MjBjMWUyMjU2Njg5ZjNmMjNhZjU4Njg2YWJjNDEwOWEyOGU2ZjZmMzkyZDIwNDM5ZjQxMTc0NzdiYjRmMjA3MWQxMjRlYTA0YmJlMWI1OTFjZGM5YWE1YTU5MDQ5MmQ0ZWE5NDdlNTNhNTBjZGZjNWQ2M2MyNWRlN2VhNzJhOWVlODg3ZmYzZmJjNzNlMWI1YzExYzk1MWRiNjhlY2QwOGFmZWZlYmEwNTk1NmU3MDI0NDEzY2E0NjdlNjkzNDViNWEzOTY4ZGM4M2Y0ZDk1ZGI4YWRiM2FlMjlmNGMyNDRjNjIwMTBmOWUxOTUwYjQ3ODg3OGQyYzAwZWUzY2U0ZGViMDMxZGE5YjlhMTZhNWRhMjdkNTRlMWQxNjExYjUwZGVkNzZkMGZmNWQ0YTg1ODFkN2NjNTEzODYyMGQ5OGYwZDlhODJmMTE4YWRlZTM1YzgwNDAxYTcwNzY1ZDNmY2ZkNTdjNGY4NzNhMzhhZTA4OWFmMDAxMTMyYWNmZjM0NTdhZDczYjhkOTJhNGIxMzMxNzQ3ZTMwYmQ4Njg2MGRkMDEwOGM0ZmNkMzU4M2I4YjI1NDdiMjU0OTdmZjNkMTYyZTU5MzFlODNkN2ZjZmZjYjhjYzUxNjY1NGMwMjA0MDk3YTNiNDM0YzFlNDdkZDU1ODZkN2ZlMTBkNWNkNWRmOGYyOWQ0NTk2MmMxMGYzYTE1MTJhNDM5M2M5YWI0ZmQ4MmYwYjFjMzRlNDJiMGJkNDY3YWFjMGU0OGI2YTJkMmUzZDA3ZWIxNmJmM2I5NWViNzk1MzEwZTBhNDUyZjdkYTMzMjhhNWVlZjJkN2M0MjUxZWRjY2ZmNDY2OTI1NjdlMGExMThkNjkyNGNkMGYzZjllYjEwZTAzYmMzMGZmMmQ0NDBjZGVkOWJkZGRjNjdkZmJlYjZjY2ExODk1Zjc3ZjQzNDZhMDdlNmM5M2ZlOWVjZTFkY2IyMDk2ODcwODhhMzM3ZTJhYTMzNWQyMjE4ZmIwZmUyNWYyYTFiYzc3MDgxNjZmYWM3ODJjOGQwYTc1NmQ2NmFmNDhmYjEzNTIwYzhmYjIxYjgzYmY4ZGRlYTI3MTA4YjAzZDA0OWJlYjUwZmQ1YTU5OTE0MzIwMWMxOTM4OTk4OWRjYjVmMmFkNWU4OGFmZGM2YmJlZmFjYjVhNDE1NGZmYjRmNWNjYmE3YWYwNzcxMDUxODU4NTM3YzdiNzhmYWUyNmE4ZDFjZmIzMjRiN2I4ZGZlNTE2NzBlZTUyMDA1Y2Y4Mjg4MzhkOTAwMDYxNGIyNTExZTZhNDM2Yzg1NmZhODY2YWE1YzFjY2E1Y2NkNjVkYmNiY2IzYTFiZmM4OWY1NGVlOWNjMzhmM2U3MThlYTFhMGYwMTJjNzAwMGU4MzlmZDdhOTc0MDdlY2FiODVkMGVhOTc2MDg4NWU4YjJlYjM2MTAzMmQ1ZDc4N2FhY2Q5NWQ1NmIxMjkzMGMwY2EyZDhkZmFiZmI2NWI0MDEyNmJmZDRjZGNlNDgyNjg5ZmMzNzJiOThmNzdjNzE5NWJjZTZkYTY2MzYxZjY1OTdmZTM0YjhhMDYzNDQwYmM2Y2MwZTYyZjM0NzEyYmJmZDhjN2MwZTM2Zjk0NDBiYzZjYzBlNjJmMzQ3NGFmNDY5YTg5MDFjYzA4MzVjYmUyYTMzMmI2YWEwYWJhN2Y4NjVjMjg2NzNiYzA0YjlmZGRjNTFlMDNmMDkzNjhiMmJkNTVjZmFhZDM4M2MzZjA1MTA2NGMzOWUzZTQwYzczNjRjNmE3NWI4OTNmZThmMTM5ZTRkMDE2YjJkMDVmNTdmZTg0YWI2OGZkMDYyNjlmZWRmYzYyYTg0YzM0YzgxNzRkYjI2ZGFlOGExYTlmN2JjNjIzNjUxNGI5MDhmZTQyYjM0ODE1MjRlYWIwMmIzOTNlOTk0OWZlYzFmZmE4YzBkNTU5MDQwMGRiNTE0ODI0ZjBhMWQyZDAxMWExM2M1ZDUxZDhiNzRhMTg4YWY=</encrypt></jdpay>
     */
    public function jd()
    {
        $xml = file_get_contents('php://input');
        $returnStatus = 'fail';
        $jdConfig = OrdersLib::getPayConfig('jd');

        if ((new PayCheckSign)->jd($xml, $data, $jdConfig))
        {
            /**
             * merchant 商户号
             * status  交易状态 2-成功
             * tradeType 交易类型 0-消费，1-退款
             * amount 支付总金额 商户订单的资金总额。单位：分，大于0
             * payType 支付方式 0-银行卡,1-白条,2-余额,3-优惠券,5-小金库,6-钢镚,8-白条分期,9-白条支付（不分期)
             * currency 交易币种 货币类型，固定填CNY
             * tradeTime 交易时间 订单生成时间。格式：“yyyyMMddHHmmss”
             */
            if ($data['result']['code'] === '000000' && $data['result']['desc'] === 'success'
                && $data['merchant'] === $jdConfig['merchant'] && $data['status'] == 2
                && $data['tradeType'] == 0 && $data['version'] === $jdConfig['version'])
            {
                $out_trade_no = $data['tradeNum'];// 订单号
                $total_amount = intval($data['amount']) / 100;// 订单总金额 单位为分
                $pay_time = strtotime($data['payList']['pay']['tradeTime']);// 支付完成时间 转换为时间戳

                try {
                // 查询是否存在这个充值订单
                $rechargeOrder = (new TOrders())->where(['order_id' => $out_trade_no, 'total_amount' => $total_amount])->first();

               if ($rechargeOrder) {
                    // 如果充值并且已经支付写入叠加余额
                   (new LanmeiUserAccount())->where(['uid' => $rechargeOrder['uid']])->increment('balance', $total_amount)->increment('total_amount', $total_amount);
                     // 获取用户账户最新的信息
                    $accountInfos =   (new LanmeiUserAccount())->where('uid', $rechargeOrder['uid'])->get(['id','uid','total_amount','balance'])->toArray();
                        // 账户流水
                        $recordData = [
                            'create_time' => time(),
                            'record_type' => 10,
                            'gid' => $rechargeOrder['gid'],
                            'price' => $total_amount,
                            'balance' => $accountInfos['balance'],
                            'account_id' => $accountInfos['id'],
                            'extend' => '用户充值记录'
                        ];
                     // 并且写入流水清单
                    (new LanmeiUserAccountRecord())->create($recordData);
                    $returnStatus = 'success';
                    echo $returnStatus;
                    exit;
                } else {
                    // 如果不是充值订单检查服务订单
                    $order = (new OrdersModel())->where(['order_id' => $out_trade_no, 'total_amount' => $total_amount])->first();
                }
                  } catch (\Exception $e) {
                      $order = [];
                     \Log::info('ali支付回调，获取订单信息失败：' . $e->getMessage());
              }
                //检查订单类型
                $num = $this->check_type($out_trade_no);

                if (!empty($order) && $order['status'] == 0)
                {
                    // 回调逻辑处理
                    $dbStatus = $this->notify_handle([
                        'oid' => $order['id'],
                        'uid' => $order['uid'],
                        'reid' => $order['reid'],
                        'fid' => $order['fid'],
                        'num' => $num,
                        'order_id' => $out_trade_no,
                        'pay_time' => $pay_time,
                        'orderInfo' => $order
                    ]);
                    if ($dbStatus)
                    {
                        $returnStatus = 'ok';
                    }
                }
            }
        }
        echo $returnStatus;
        exit;
    }

    /**
     * 回调后的逻辑处理
     * @param array $map
     * @return bool
     */
    public function notify_handle($map = [])
    {
        $rid = [];
        $oid = $map['oid'];
        $uid = $map['uid'];
        $reid = $map['reid'] ?? 0;
        $fid = $map['fid'] ?? 0;
        $num = $map['num'] ?? 0;
        $out_trade_no = $map['order_id'];
        $pay_time = $map['pay_time'];
        $fortune_type = 0;
        $status = 3;
        $beginTransactionStatus = true;
        DB::beginTransaction();
        try
        {
            // 修改生时校正状态
            if ($num == 1 && (int)$reid > 0)
            {
                DB::table('rectification')->where(['id' => $reid])->update(['status' => 1]);// 支付完成，等待校正
            }
            // 问答
            if (in_array($num, [5, 6]))
            {
                $res = (new LanmeiCounselorProblem())->payHandle($out_trade_no);
            }

            if ($num == 7)
            {
                 $res = (new LanmeiCounselorAnswer())->answerRead($map['uid'], $map['orderInfo']['gid'], $out_trade_no);
            }
            // 修改订单状态
            DB::table('orders')->where(['order_id' => $out_trade_no])->update(['status' => 1, 'pay_time' => $pay_time]);// 支付成功

            DB::commit();
        }
        catch (\Exception $e)
        {
            $beginTransactionStatus = false;
            DB::rollback();
        }

        // 付款成功  开始生时校正
        if ($beginTransactionStatus === true && $num == 1 && intval($reid) > 0)
        {
            try
            {
                $rectification = (new RectificationModel())->where(['id' => $reid])->first();
                $event_array   = $rectification->events()->get()->toArray();
                $recode        = (new Recode())->where(['id' => $rectification['rid']])->first();
            }
            catch (\Exception $e)
            {
                \Log::info('ali支付回调，获取生时矫正相关信息失败：' . $e->getMessage());

                $rectification = [];
                $recode = [];
                $event_array = [];
            }

            $rid = $rectification;
            $status = 2;

            if ($rectification && $event_array && $recode)
            {
                 $jobData = [
                    'oid' => $oid,
                    'order_id' => $out_trade_no,
                    'reid' => $reid,
                    'start_time' => $rectification['start_time'],
                    'end_time' => $rectification['end_time'],
                    'events' => $event_array,
                    'recode' => $recode
                ];

                $queueConfig = config('queue');
                queuePush($queueConfig['rectification_task'], $jobData, $queueConfig['rectification_queue'], $queueConfig['rectification_delay']);

//                rabbitTask('rectification',$jobData);
            }
        }

        // 付款成功  开始添加运势计算
        if ($beginTransactionStatus === true && $num == 2 && (int)$fid > 0)
        {
            try
            {
                $fortune = $this->push_fortune(['uid' => $uid, 'oid' => $oid]);
                
            }
            catch (\Exception $e)
            {
                \Log::info('ali支付回调，运势加入队列失败：' . $e->getMessage());
            }

            $rid = $fortune;
            $status = 2;
        }
        // 问答 指定时 推送 给咨询师答题信息
        if ($num == 5 && isset($res) && $res['counselorMode'] == 1 && !empty($res['push']))
        {
            // todo 推送咨询师答题 消息
        }

        // 删除订单缓存
        (new OrdersModel())->rm_cache(['type' => 4, 'order_id' => $out_trade_no, 'uid' => $uid, 'status' => $status], $rid);

        // if ($beginTransactionStatus === true)
        // {
        //     //订单支付数量增加
        //     // $OrdersModel = new OrdersModel();
        //     // $OrdersModel->inc_order_num(['order_type' => $num, 'fortune_type' => $fortune_type]);
        // }

        return $beginTransactionStatus;
    }

    /**
     * 月运和年运加入队列
     * @param array $map
     * @return bool|mixed
     * @throws \app\common\lib\exception\ApiException
     */
    public function push_fortune($map = [])
    {
        $uid = $map['uid'];
        $oid = $map['oid'];

        $where = ['o.id' => $oid];

        try
        {
            $fortune = (new OrdersModel())->from('orders as o')
                ->select('f.time','f.type','f.rids','g.expire_time','o.status','o.gid','o.uid','o.order_type','o.order_id')
                ->join('goods as g', 'o.gid','=','g.id', 'INNER')
                ->join('fortune as f', 'o.fid','=','f.id', 'INNER')
                ->where($where)
                ->whereIn('o.order_type', [2,3, 4])
                ->first();
         
        }
        catch (\Exception $e)
        {
            $fortune = [];
        }

        if ($fortune && !empty($fortune))
        {
            $rids = explode(',', $fortune['rids']);
            //年运大礼包活动
            if ($fortune['order_type'] == 4)
            {
                (new Active())->index(['uid' => $fortune['uid'], 'gid' => $fortune['gid'], 'rids' => $rids]);
            }

            $start_time = $fortune['time'];
            $end_time = strtotime($fortune['expire_time'], $fortune['time']);

            $recode_info = [];
            foreach ($rids as $rid)
            {
                //获取档案信息
                $recode_info[] = (new Recode())->getRecode(['uid' => $uid, 'id' => $rid]);
                \Log::info('recode_info:' . var_export($recode_info, true));
            }
            switch ($fortune['type'])
            {
                case 2:
                    $start_time = date('Y-m', $start_time);
                    $end_time = date('Y-m', strtotime('-1 months', $end_time));
                    break;
                case 3:
                    $start_time = date('Y', $start_time);
                    $end_time = date('Y', strtotime('-1 years', $end_time));
                    break;
                default:
                    $start_time = "";
                    $end_time = "";
                    break;
            }

            $unlock_time = prDates(['start' => $start_time, 'end' => $end_time, 'type' => $fortune['type']]);
            //将运势加入队列运算
            fortune_redis_job(['oid'=>$oid,'order_id' => $fortune['order_id'], 'recode_info' => $recode_info, 'unlock_time' => $unlock_time, 'ostatus' => $fortune['status'], 'ftype' => $fortune['type']]);
            return ['rid' => $rids, 'type' => $fortune['type']];
        } else
        {
            return false;
        }

    }

    /**
     * 判断订单类型
     * @param $order_id
     * @return int
     */
    protected function check_type($order_id)
    {

        $num = substr($order_id, 1, 1);

        return $num * 1;
    }

    /**
     * 数组转xml
     * @param $arr
     * @return string
     */
    protected function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val)
        {
            if (is_numeric($val))
            {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";

            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        return $xml;
    }

}
